import { ApplicationInsights, Util } from '@microsoft/applicationinsights-web'


export default {
    install: (app, options) => {
        const config = options.appInsightsConfig
        const appInsights = new ApplicationInsights({ config })
        appInsights.loadAppInsights()
        app.config.globalProperties.$appInsights = appInsights
        const router = options.router

        if (router) {
      
          const baseName = options.baseName || '(Vue App)'
      
          router.beforeEach( (route, from, next) => {
            const name = baseName + '/' + route.name;
            appInsights.context.telemetryTrace.traceID = Util.generateW3CId();
            appInsights.context.telemetryTrace.name = route.name;
            appInsights.startTrackPage(name)
            next()
          })
        
          router.afterEach( route => {
            const name = baseName + '/' + route.name;
            const url = location.protocol + '//' + location.host + route.fullPath;
            appInsights.stopTrackPage(name, url);
            appInsights.flush();
          })
        }
    }
}